package com.imoney.framework.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 
 * 
 * Description: <BR>
 * 
 * @author Robin Wu CreateTime: Nov 22, 2010
 */
public class WebContext {

	private static final ThreadLocal<WebContext> threadContext = new ThreadLocal<WebContext>();
	private HttpServletRequest request;
	private HttpServletResponse response;
	private HttpSession session;

	/**
	 * 
	 * Constructor
	 * 
	 * @param request
	 * @param response
	 */
	private WebContext(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
		this.session = request.getSession();
	}

	public HttpServletRequest getRequest() {
		return this.request;
	}

	public HttpServletResponse getResponse() {
		return this.response;
	}

	public HttpSession getSession() {
		return this.session;
	}

	public Object getAttributeFromSession(String name) {
		return session.getAttribute(name);
	}

	public Object getAttributeFromRequest(String name) {
		return request.getAttribute(name);
	}

	public Map<String, String[]> getParameterMapFromRequest() {
		return request.getParameterMap();
	}

	/**
	 * 
	 * Description: <BR>
	 * invoke by filter for involving request and response
	 * 
	 * @param request
	 * @param response
	 */
	public static void init(HttpServletRequest request,
			HttpServletResponse response) {
		WebContext context = threadContext.get();
		if (context != null) {
			context = new WebContext(request, response);
		}
		threadContext.set(context);
	}

	/**
	 * 
	 * Description: <BR>
	 * invoke by WebContextUtils or other Class for get WebContext instance
	 * 
	 * @return
	 */
	public static WebContext getContext() {
		WebContext context = threadContext.get();
		return context;
	}

}
